package com.xrit.sunnyday.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Member;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.utils.SMSUtils;
import com.xrit.sunnyday.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @PostMapping("/check")
    public Result checkMember(@RequestBody Map<String,String> paramMap, HttpServletResponse res){
        //从redis连接池中获取链接
        Jedis jedis = jedisPool.getResource();
        //取出用户传过来的手机号码
        String telephone = paramMap.get("telephone");
        //验证码的 key
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
        //获取redis中的验证码，key对应的value
        String codeInRedis = jedis.get(key);
        //判断验证码是否存在
        if(StringUtils.isEmpty(codeInRedis)){
            //没有 重新发送
            return new Result(false, "请重新获取验证码!");
        }
        //有  跟前端传的验证码对比是否一致
        String validateCode = paramMap.get("validateCode");
        if(!codeInRedis.equals(validateCode)){
            //不一致
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //一致 移除redis中的验证码，防止重复提交，
        jedis.close();

        //通过手机号判断是否为会员
        Member member = memberService.findByTelephone(telephone);
        if(null == member){
            //非会员：填充会员信息
            member = new Member();
            member.setRegTime(new Date());      //注册时间
            member.setPhoneNumber(telephone);   //注册手机号码
            member.setRemark("手机快速注册");     //标记
            //添加为新会员
            memberService.add(member);
        }
        //是会员：跟踪记录的手机号码，代表着会员
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setMaxAge(30*24*60*60); // 存1个月
        cookie.setPath("/"); // 访问的路径 根路径下时 网站的所有路径 都会发送这个cookie
        res.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }




}
